package com.cn.crmsystem.intercept;


import com.cn.crmsystem.exception.TokenExpiredException;
import com.cn.crmsystem.pojo.Login;
import com.cn.crmsystem.service.systemService.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckTokenIntercept implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;

    //拦截实现的方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("========  CheckTokenIntercept  拦截器 ================ ");
        //  响应的设置
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin")); // *允许任意地址访问，当前解决跨域后携带cookie问题
        response.setHeader("Access-Control-Allow-Credentials", "true"); //是否包含cookie，如果不包含，可省略
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PATCH,PUT,OPTIONS,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization,Cookie,Accept,Token,Origin");
        //获得头部信息
        String token = request.getHeader("authorization");
        //
        System.out.println("111111111"+token);
        if (token != null && token.trim().length() > 0) {//   如果   没有token  没登录  有 token 数据库没有   跳Exception控制器
            //验证数据库  中是否存在
            //把用户保存shiro
            Login login = (Login) SecurityUtils.getSubject().getPrincipal();//29
            //延长生命  token
            System.out.println(login.getUserName());
            String redisToken = loginService.checkToken(login.getUserName());
            if (token.equals(redisToken)) {
                request.setAttribute("login", login);//设置用户信息在request
                return true;
            }
            throw new TokenExpiredException();
        }
        request.setAttribute("msg","未登录");
        request.getRequestDispatcher("/notLogin").forward(request,response);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
